# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        l1 = 0
        l2 = 0
        p1, p2 = headA, headB
        while p1:
            l1 += 1
            p1 = p1.next
            
        while p2:
            l2 += 1
            p2 = p2.next
        p1, p2 = headA, headB    
        diff = l1 - l2
        if diff > 0: 
            for i in range(l1 - l2):
                p1 = p1.next
        else:
            for i in range(l2 - l1):
                p2 = p2.next
        while p1 != p2:
            p1 = p1.next
            p2 = p2.next
        return p1
        
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        p1,p2 = headA,headB
        while p1 != p2:
            if p1 == None:
                p1 = headB
            else:
                p1 = p1.next
            
            if p2 == None:
                p2 = headA
            else:
                p2 = p2.next
        return p1
        
                

            